<template>
  <a-layout-header class="global-header">
    <div class="header-content">
      <!-- 左侧 Logo 和标题 -->
      <div class="header-left">
        <div class="logo-section" @click="toHome">
          <img src="@/assets/logo.png" alt="Logo" class="logo" />
          <span class="site-title">ZeroCodeGenerator</span>
        </div>
        
        <!-- 导航菜单 -->
        <a-menu
          v-model:selectedKeys="selectedKeys"
          mode="horizontal"
          class="header-menu"
          :items="filterMenuItems"
          @click="handleMenuClick"
        />
      </div>
      <!-- 右侧用户区域 -->
      <div class="header-right">
        <div v-if="loginUserStore.loginUser.id">
          <!-- Dropdown 下拉菜单 -->
          <a-dropdown>
            <a-space>
              <a-avatar :src="loginUserStore.loginUser.userAvatar"/>
              {{ loginUserStore?.loginUser.userName ?? '无名氏' }}
            </a-space>
            <!-- 菜单项 -->
            <template #overlay>
              <a-menu>
                <a-menu-item @click="toUserProfilePage">
                  <UserOutlined />
                  个人信息
                </a-menu-item>
                <a-menu-item @click="changePassword">
                  <LockOutlined />
                  修改密码
                </a-menu-item>
                <a-menu-item @click="doLogout">
                  <LogoutOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
        <div v-else>
          <a-button type="primary" @click="handleLogin">登录</a-button>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <ChangePasswordModal
      v-model:open="changePasswordModalVisible"
      @success="handlePasswordChangeSuccess"
    />
  </a-layout-header>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message, type MenuProps } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/LoginUserStore.ts'
import { userLogout } from '@/api/userController';
import { UserOutlined,LogoutOutlined,LockOutlined } from '@ant-design/icons-vue'
import ChangePasswordModal from '@/components/ChangePasswordModal.vue'

//获取登录态
const loginUserStore = useLoginUserStore();

const router = useRouter()
const route = useRoute()

// 当前选中的菜单项
const selectedKeys = ref<string[]>([])

// 菜单配置（原始菜单项，未经过过滤）
const originMenuItems = [
  {
    key: 'home',
    label: '首页',
    title: '首页'
  },
  {
    key: 'userManagement',
    label: '用户管理',
    title: '用户管理'
  },
  {
    key: 'appManagement',
    label: '应用管理',
    title: '应用管理',
  },
  {
    key: 'chatHistoryManagement',
    label: '对话历史管理',
    title: '对话历史管理'
  },
  // {
  //   key: 'about',
  //   label: '关于',
  //   title: '关于'
  // }
]

// 处理菜单点击
const handleMenuClick: MenuProps['onClick'] = (e) => {
  const key = e.key as string
  // 根据菜单项导航到对应路由
  switch (key) {
    case 'home':
      router.push('/')
      break
    case 'userManagement':
      router.push('/admin/userManagement')
      break
    case 'appManagement':
      router.push('/admin/appManagement')
      break
    case 'chatHistoryManagement':
      router.push('/admin/chatHistoryManagement')
      break  
    case 'about':
      router.push('/user/about')
      break
  }
}

// 处理登录按钮点击
const handleLogin = () => {
  router.push("/user/login")
}

// 用户注销
const doLogout = async () => {
  const res = await userLogout();
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败，' + res.data.message)
  }
}
// 跳转到个人信息页面
const toUserProfilePage = () => {
  router.push('/user/profile')
}

// 修改密码弹窗控制
const changePasswordModalVisible = ref(false)

// 修改密码，弹出修改密码弹窗
const changePassword = () => {
  changePasswordModalVisible.value = true
}

// 密码修改成功后的回调
const handlePasswordChangeSuccess = async () => {
  // 密码修改成功后，清空登录状态并跳转到登录页
  loginUserStore.setLoginUser({
    userName: '未登录',
  })
  await router.push('/user/login')
}

// 监听路由变化，更新选中的菜单项（通过底部下划线显示当前选中的菜单项）
watch(() => route.path, (newPath) => {
  switch (newPath) {
    case '/':
      selectedKeys.value = ['home']
      break
    case '/admin/userManagement':
      selectedKeys.value = ['userManagement']
      break
    case '/admin/appManagement':
      selectedKeys.value = ['appManagement']
      break
    case '/admin/chatHistoryManagement':
      selectedKeys.value = ['chatHistoryManagement']
      break  
    case '/user/about':
      selectedKeys.value = ['about']
      break
    default:
      selectedKeys.value = []
  }
}, { immediate: true })

// 过滤菜单项,如果当前用户没有登录，或登录用户不是管理员，就不展示管理导航栏菜单项
const filterMenus = (menus = [] as MenuProps['items']) => {
  return menus?.filter((menu) => {
    const menuKey = menu?.key as string
    //TODO：过滤handleMenuClick方法中的菜单项menu，只要key中包含Management即认定为需要管理员权限才可访问
    if (menuKey?.includes('Management')) {
      const loginUser = loginUserStore.loginUser
      if (!loginUser || loginUser.userRole !== 'admin') {
        return false
      }
    }
    return true
  })
}

// 展示在菜单的路由数组（过滤后的菜单项）
const filterMenuItems = computed<MenuProps['items']>(() => filterMenus(originMenuItems))


//点击导航栏左侧Logo图标跳转到首页
const toHome = ()=>{
  router.push("/");
}
</script>

<style scoped>
.global-header {
  /* 半透明白，实现毛玻璃通透感 */
  background: rgb(255, 255, 255, 0.15); 
  backdrop-filter: blur(30px);
  -webkit-backdrop-filter: blur(40px);
  padding: 0;
  height: 64px;
  line-height: 64px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  height: 100%;
}

.header-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.logo-section {
  display: flex;
  align-items: center;
  margin-right: 40px;
}

.logo {
  width: 32px;
  height: 32px;
  margin-right: 12px;
  border-radius: 20%;
  overflow: hidden; /* 确保图片内容不会超出圆形边界 */
  object-fit: cover; /* 如果.logo是img标签，这个属性可以让图片适应容器 */
}

.site-title {
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
  white-space: nowrap;
}

.header-menu {
  border-bottom: none;
  background: transparent;
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    padding: 0 16px;
  }
  
  .logo-section {
    margin-right: 20px;
  }
  
  .site-title {
    font-size: 16px;
  }
  
  .header-menu {
    display: none;
  }
}

@media (max-width: 480px) {
  .site-title {
    display: none;
  }
  
  .logo-section {
    margin-right: 0;
  }
}
</style>